package com.glsc.ngateway.ldap.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.enums.AppEhrStatus;
import com.glsc.ngateway.common.api.ldap.dto.*;
import com.glsc.ngateway.common.api.ldap.resp.AppEhrResponse;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.ldap.LdapEhrDept;
import com.glsc.ngateway.common.base.domain.mysql.gateway.ldap.LdapEhrEmp;
import com.glsc.ngateway.common.base.enums.OaHrmresourceStatusEnum;
import com.glsc.ngateway.ldap.schedule.ScheduledJobs;
import com.glsc.ngateway.ldap.service.LdapEhrCompService;
import com.glsc.ngateway.ldap.service.LdapEhrDeptService;
import com.glsc.ngateway.ldap.service.LdapEhrEmpService;
import io.swagger.annotations.Api;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/ehr")
@Api(value = "flowable流程ehr类", tags = {"flowable流程ehr类"})
public class LdapEhrController {

    private static Logger logger = LoggerFactory.getLogger(LdapEhrController.class);

    @Resource
    LdapEhrEmpService ldapEhrEmpService;
    @Resource
    LdapEhrDeptService ldapEhrDeptService;
    @Resource
    LdapEhrCompService ldapEhrCompService;
    @Resource
    ScheduledJobs scheduledJobs;

    @RequestMapping(method = RequestMethod.GET, value = "/getUserList")
    public LdapResponse<List<LdapEhrEmp>> getUserList(@RequestParam(value = "department", required = false) String department,
                                                      @RequestParam(value = "filteAlive", required = false) boolean filteAlive) {
        List<LdapEhrEmp> emplist = ldapEhrEmpService.getUserListByDept(department);
        if (filteAlive) {
            emplist = emplist.stream().filter(emp -> OaHrmresourceStatusEnum.isAlive(emp.getStatus())).collect(Collectors.toList());
        }
        return LdapResponse.success(emplist);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/queryEhr")
    public LdapResponse<List<LdapEhrEmpDto>> getUserList(@RequestBody LdapEhrEmpSearchDto param) {
        List<LdapEhrEmpDto> ehrlist = ldapEhrEmpService.findAll(param);
        if (CollectionUtil.isNotEmpty(ehrlist)) {
            Map<Integer, LdapEhrDeptDto> depMap = ldapEhrDeptService.findAll().stream().collect(Collectors.toMap(LdapEhrDeptDto::getDepid, o -> o));
            ehrlist.forEach(ehr -> ehr.setDeptinfo(depMap.get(ehr.getDepid())));
        }
        return LdapResponse.success(ehrlist);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/queryDept")
    public LdapResponse<List<LdapEhrDeptDto>> getDepartmentList(@RequestBody LdapEhrDeptSearchDto param) throws Exception {
        return LdapResponse.success(ldapEhrDeptService.findAll(param));
    }

    /**
     * simple条件查询部门信息,只简单的根据domain中的值进行查找，不包含任何关联业务逻辑
     *
     * @param condition
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST, value = "/findDeptByCondition")
    public LdapResponse<List<LdapEhrDeptDto>> findDeptByCondition(@RequestBody LdapEhrDeptDto condition) throws Exception {
        return LdapResponse.success(ldapEhrDeptService.findDeptByCondition(condition));
    }

    @RequestMapping(method = RequestMethod.POST, value = "/queryComp")
    public LdapResponse<List<LdapEhrCompDto>> getCompanyList(@RequestBody LdapEhrCompSearchDto param) {
        return LdapResponse.success(ldapEhrCompService.findAll(param));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getDepartmentList")
    public LdapResponse<List<LdapEhrDeptDto>> getDepartmentList(@RequestParam(value = "findAll", required = false) Boolean findAll ) {
        List<LdapEhrDeptDto> list = ldapEhrDeptService.findAll();
        if (findAll != null && !findAll) {
            list = list.stream().filter(u -> !"1".equals(u.getCanceled())).collect(Collectors.toList());
        }
        return LdapResponse.success(list);
    }

    @GetMapping("getChineseName")
    public AppEhrResponse<String> getChineseName(@RequestParam("userId") String userId) {
        AppEhrResponse<String> appEhrResponse = new AppEhrResponse<>();
        try {
            String name = ldapEhrEmpService.getChineseName(userId);
            if (Strings.isBlank(name)) {
                appEhrResponse.setUserTip("未查询到该用户信息" + userId);
                appEhrResponse.setErrorMsg("未查询到该用户信息" + userId);
                appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
            } else {
                appEhrResponse.setErrorMsg("查询成功");
                appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
                appEhrResponse.setData(name);
            }
        } catch (Exception e) {
            logger.error("ehr查询人员名称getChineseName返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户信息" + userId);
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //获取部门或者二级部人员列表
    @GetMapping("getGroupById")
    public List<String> getGroupById(@RequestParam("depid") Integer depid) {
        try {
            return ldapEhrEmpService.getGroupById(depid).stream().map(LdapEhrEmp::getBadge).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("ehr获取部门或者二级部人员列表错误，请查看！", e);
            return Collections.EMPTY_LIST;
        }
    }

    //获取部门或者二级部该岗位的人员列表
    @GetMapping("getJobGroup")
    public List<String> getJobGroup(@RequestParam("depid") Integer depid, @RequestParam("jobId") Integer jobId) {
        try {
            return ldapEhrEmpService.getJobGroup(depid, jobId).stream().map(LdapEhrEmp::getBadge).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("ehr获取部门或者二级部该岗位的人员列表错误，请查看！", e);
            return Collections.EMPTY_LIST;
        }
    }


    @GetMapping("getDirectLeader")
    public String getDirectLeader(@RequestParam("userId") String userId) {
        LdapEhrEmpDto ldapEhr = ldapEhrEmpService.getLdapEhrWithDeptInfo(userId);
        return Objects.nonNull(ldapEhr) ? ldapEhr.getDeptinfo().getLeader() : null;
    }

    @GetMapping("getDeptLeader")
    public String getDeptLeader(@RequestParam("userId") String userId) {
        String result = null;
        LdapEhrEmpDto ldapEhr = ldapEhrEmpService.getLdapEhrWithDeptInfo(userId);
        if (Objects.nonNull(ldapEhr)) {
            LdapEhrDeptDto deptTmp = ldapEhr.getDeptinfo();
            while (deptTmp.getParentDeptInfo() != null) {
                deptTmp = deptTmp.getParentDeptInfo();
            }
            result = deptTmp.getLeader();
        }
        return result;
    }

    //人员信息
    @GetMapping("getemp")
    public AppEhrResponse<LdapEhrEmpDto> getLdapEhrEmp(@RequestParam(value = "account", required = false) String account,
                                                       @RequestParam(value = "userId", required = false) String userId,
                                                       @RequestParam(value = "filteAlive", required = false) boolean filteAlive) {
        AppEhrResponse<LdapEhrEmpDto> appEhrResponse = new AppEhrResponse<>();

        account = Strings.isNotBlank(account) ? account : userId;
        try {
            LdapEhrEmpDto ldapEhr = ldapEhrEmpService.findByBadge(account);
            if (ldapEhr == null) {
                appEhrResponse.setUserTip("未查询到该用户");
                appEhrResponse.setErrorMsg("未查询到该用户");
                appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
            } else if (filteAlive && !OaHrmresourceStatusEnum.isAlive(ldapEhr.getStatus())) {
                appEhrResponse.setUserTip("该用户已离职或退休无法查询");
                appEhrResponse.setErrorMsg("该用户已离职或退休无法查询");
                appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
            } else {
                appEhrResponse.setErrorMsg("查询成功");
                appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
                appEhrResponse.setData(ldapEhr);
            }
        } catch (Exception e) {
            logger.error("ehr查询人员信息getemp返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //查多人信息
    @PostMapping("getemps")
    public AppEhrResponse<List<LdapEhrEmp>> getLdapEhrEmps(@RequestBody List<String> userId) {
        AppEhrResponse<List<LdapEhrEmp>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrEmp> tAmEhrEmp = ldapEhrEmpService.findByBadge(userId);
            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(tAmEhrEmp);
        } catch (Exception e) {
            logger.error("ehr查询多个人员信息getemps返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //查多人信息
    @PostMapping("getEmpsByAccounts")
    public AppEhrResponse<List<LdapEhrEmpDto>> getEmpsByAccounts(@RequestBody List<String> userAccounts) {
        AppEhrResponse<List<LdapEhrEmpDto>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrEmpDto> tAmEhrEmp = ldapEhrEmpService.getEmpByAccounts(userAccounts);
            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(tAmEhrEmp);
        } catch (Exception e) {
            logger.error("ehr查询多个人员信息getemps返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //通过部门查多人
    @PostMapping("getEmpsByDepts")
    public AppEhrResponse<List<LdapEhrEmpDto>> getEmpsByDepts(@RequestBody List<String> depts) {
        AppEhrResponse<List<LdapEhrEmpDto>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrEmpDto> tAmEhrEmp = ldapEhrEmpService.getEmpByDepts(depts);
            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(tAmEhrEmp);
        } catch (Exception e) {
            logger.error("ehr查询多个人员信息getemps返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    @GetMapping("getAllEmps")
    public AppEhrResponse<List<LdapEhrEmpDto>> getAllEmps(@RequestParam(value = "findAll", required = false) Boolean findAll ) {
        List<LdapEhrEmpDto> list = ldapEhrEmpService.findAll();
        if (findAll != null && !findAll) {
            list = list.stream().filter(u -> OaHrmresourceStatusEnum.isAlive(u.getStatus())).collect(Collectors.toList());
        }
        return AppEhrResponse.instanceOfSuccss(list);
    }

    //查部门
    @GetMapping("getempdept")
    public AppEhrResponse<LdapEhrEmpDto> gettAmEhrEmpDept(@RequestParam("userId") String userId) {
        AppEhrResponse<LdapEhrEmpDto> appEhrResponse = new AppEhrResponse<>();
        try {
            LdapEhrEmpDto ldapEhr = ldapEhrEmpService.getLdapEhrWithDeptInfo(userId);
            if (ldapEhr == null) {
                appEhrResponse.setUserTip("未查询到该用户组织信息");
                appEhrResponse.setErrorMsg("未查询到该用户组织信息");
                appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
            } else {
                appEhrResponse.setErrorMsg("查询成功");
                appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
                appEhrResponse.setData(ldapEhr);
            }
        } catch (Exception e) {
            logger.error("ehr查询部门信息getempdept返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户组织信息");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //查部门
    @GetMapping("getAllDept")
    public AppEhrResponse<List<LdapEhrDeptDto>> getAllDept(@RequestParam(value = "findAll", required = false) Boolean findAll) {
        AppEhrResponse<List<LdapEhrDeptDto>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrDeptDto> allDept = ldapEhrDeptService.findAll();
            if (findAll != null && !findAll) {
                allDept = allDept.stream().filter(u -> !"1".equals(u.getCanceled())).collect(Collectors.toList());
            }
            if (allDept == null) {
                appEhrResponse.setUserTip("未查询到该用户组织信息");
                appEhrResponse.setErrorMsg("未查询到该用户组织信息");
                appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
            } else {
                appEhrResponse.setErrorMsg("查询成功");
                appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
                appEhrResponse.setData(allDept);
            }
        } catch (Exception e) {
            logger.error("ehr查询部门信息getempdept返回错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户组织信息");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }

        return appEhrResponse;
    }

    @RequestMapping("findUserListByUserLeaderAccount")
    public AppEhrResponse<List<LdapEhrEmpDto>> findUserListByUserLeaderAccount(@RequestParam("userAccount") String userAccount) {
        AppEhrResponse<List<LdapEhrEmpDto>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrEmpDto> tAmEhrEmp = ldapEhrEmpService.findUserListByUserLeaderAccount(userAccount);
            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(tAmEhrEmp);
        } catch (Exception e) {
            logger.error("ehr领导下属错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    @RequestMapping("findUserListByUserLeaderAccountList")
    public AppEhrResponse<List<LdapEhrEmpDto>> findUserListByUserLeaderAccountList(@RequestBody List<String> userAccountList) {
        AppEhrResponse<List<LdapEhrEmpDto>> appEhrResponse = new AppEhrResponse<>();
        try {
            List<LdapEhrEmpDto> tAmEhrEmp = ldapEhrEmpService.findUserListByUserLeaderAccountList(userAccountList);
            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(tAmEhrEmp);
        } catch (Exception e) {
            logger.error("ehr领导下属错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    //查部门
    @GetMapping("tongbu")
    public AppEhrResponse<?> tongbu() {
        scheduledJobs.syncEhrDataTask();
        return AppEhrResponse.instanceOfSuccss();
    }


    /**
     * 获取人员的部门信息
     */
    @RequestMapping(value = "/getDepByAccount")
    public AppEhrResponse<LdapEhrDeptDto> getDepByAccount(@RequestParam("account") String account) {
        AppEhrResponse<LdapEhrDeptDto> appEhrResponse = new AppEhrResponse<>();
        try {
            LdapEhrDeptDto dept = ldapEhrDeptService.findByBadge(account);

            appEhrResponse.setErrorMsg("查询成功");
            appEhrResponse.setStatus(AppEhrStatus.Success.getErrorCode());
            appEhrResponse.setData(dept);
        } catch (Exception e) {
            logger.error("ehr查询部门信息错误，请查看！", e);
            appEhrResponse.setUserTip("未查询到该用户");
            appEhrResponse.setErrorMsg(e.getMessage());
            appEhrResponse.setStatus(AppEhrStatus.Fail.getErrorCode());
        }
        return appEhrResponse;
    }

    @RequestMapping(value = "/getDepartmentInfoList", method = RequestMethod.POST)
    public LdapResponse<List<LdapEhrDept>> getDepartmentInfoList(@RequestBody List<Integer> oaDepartmentIdList) {
        logger.info("查询OA用户列表，状态是：{}", oaDepartmentIdList);
        return LdapResponse.success(ldapEhrDeptService.findAllByOaDeptIds(oaDepartmentIdList));
    }

    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public LdapResponse<Void> save(@RequestBody List<LdapEhrEmpDto> data) {
        ldapEhrEmpService.save(data);
        return LdapResponse.success("成功", null);
    }

    @RequestMapping(value = "/getByOaUserIdList", method = RequestMethod.POST)
    public LdapResponse<List<LdapEhrEmpDto>> getByOaUserIdList(@RequestBody List<Integer> oaUserIdList) {
        return LdapResponse.success(ldapEhrEmpService.findByOaUserIdList(oaUserIdList));
    }
}
